<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/jquery.js"></script>
</head>
<body>
    <input type="text" placeholder="用户名" class="uname" value="admin" />
    <input type="text" placeholder="密码" class="pwd" value="123456" />
    <button class="btn">登录</button>
    <button class="user">用户信息 接口</button>
    <button class="logout">退出</button>
    <script>
        $('.btn').click(()=>{
            let uname = $('.uname').val();
            let pwd = $('.pwd').val();
            $.ajax({
                url:'http://localhost:3000/login',
                type:'post',
                data:{
                    uname,
                    pwd
                },
                success: (res)=>{
                    console.log(res);
                    if(res.status == 200) {
                        localStorage.setItem('token',res.token)
                    }
                }
            })
        })

        $('.user').click(()=>{
            let mytoken = localStorage.getItem('token') || '';
            let token = 'Bearer ' + mytoken;
            $.ajax({
                url:'http://localhost:3000/api/user',
                headers: {
                    Authorization: token,
                },
                success: (res)=>{
                    console.log(res)
                }
            })
        })

        $('.logout').click(()=>{
            let mytoken = localStorage.getItem('token') || '';
            let token = 'Bearer ' + mytoken;

            $.ajax({
                url:'http://localhost:3000/logout',
                headers: {
                    Authorization: token,
                },
                success: (res)=>{
                    console.log(res);
                    if(res.status == 200) {
                        localStorage.removeItem('token');
                        setTimeout(()=>{
                            window.location.href='./login.html'
                        })
                    }
                }
            })
        })
    </script>
</body>
</html>